<!--
 * @Description: 商品分类参数模块
 * @Author: pinus
 * @Email: pinus0716@163.com
 * @Git: https://gitee.com/xyf97
 * @Date: 2021-10-01 11:22:07
 * @LastEditTime: 2021-10-02 10:45:40
-->
<template>
  <div class="params-container">
    <!--  头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/wlecome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容card -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类添加参数信息！"
        type="warning"
        show-icon
        close-text="知道了">
      </el-alert>
      <!-- 选择商品分类 -->
      <div class="select_cate">
        <span>选择商品分类：</span>
        <el-cascader v-model="cascader_value"
          :options="categories"
          :props="cascaderProps"
          @change="handelChange"
          clearable
          size="small"></el-cascader>
      </div>
      <!-- 属性选项卡 -->
      <el-tabs v-model="sel"
        type="card"
        @tab-click="handleClick">

        <!-- 动态参数 -->
        <el-tab-pane label="动态参数"
          name="many">
          <el-row>
            <el-col>
              <el-button type="primary"
                @click="addAttributes">添加参数</el-button>
            </el-col>
          </el-row>
          <el-table :data="attributes"
            border
            stripe>
            <el-table-column type="expand">
              <template scope="scope">
                <el-row>
                  <el-col>
                    <!-- 已有标签 -->
                    <el-tag :key="tag"
                      v-for="tag in scope.row.attr_vals"
                      closable
                      :disable-transitions="false"
                      @close="handleClose(scope.row, tag)">
                      {{tag}}
                    </el-tag>
                    <!-- 添加新标签 -->
                    <el-input class="input-new-tag"
                      v-if="inputVisible"
                      v-model="inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)">
                    </el-input>
                    <el-button v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput">+ New Tag</el-button>

                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column type="index"
              label="#"></el-table-column>
            <el-table-column label="参数名称"
              prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template scope="scope">
                <el-button type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="openEditDialog(scope.row.attr_name)">编辑</el-button>
                <el-button type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="(removeAttr(scope.row.attr_id))">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数"
          name="only">
          <el-row>
            <el-col>
              <el-button type="primary"
                @click="addAttributes">添加属性</el-button>
            </el-col>
          </el-row>
          <el-table :data="attributes"
            border
            stripe>
            <el-table-column type="expand">
              <template scope="scope">
                <el-row>
                  <el-col>
                    <!-- 已有标签 -->
                    <el-tag :key="tag"
                      v-for="tag in scope.row.attr_vals"
                      closable
                      :disable-transitions="false"
                      @close="handleClose(scope.row, tag)">
                      {{tag}}
                    </el-tag>
                    <!-- 添加新标签 -->
                    <el-input class="input-new-tag"
                      v-if="inputVisible"
                      v-model="inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)">
                    </el-input>
                    <el-button v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput">+ New Tag</el-button>

                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column type="index"
              label="#"></el-table-column>
            <el-table-column label="属性名称"
              prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template scope="scope">
                <el-button type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="openEditDialog(scope.row.attr_name)">编辑</el-button>
                <el-button type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="(removeAttr(scope.row.attr_id))">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加新参数对话框 -->
      <el-dialog title="添加新属性"
        :visible.sync="addDialogVisible"
        width="50%"
        :before-close="closeAddAttrDialog">
        <el-form :model="addAttrForm"
          :rules="addRules"
          ref="addAttrForm">
          <el-form-item label="活动名称"
            prop="attr_name">
            <el-input v-model="addAttrForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
          class="dialog-footer">
          <el-button @click="closeAddAttrDialog">取 消</el-button>
          <el-button type="primary"
            @click="submitNewAttr">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑参数对话框 -->
      <el-dialog title="编辑参数"
        :visible.sync="editDialogVisible"
        width="50%"
        :before-close="closeEditAttrDialog">
        <el-form :model="editAttrForm"
          :rules="addRules"
          ref="editAttrForm">
          <el-form-item label="活动名称"
            prop="attr_name">
            <el-input v-model="editAttrForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
          class="dialog-footer">
          <el-button @click="closeEditAttrDialog">取 消</el-button>
          <el-button type="primary"
            @click="submitNewAttr">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'GoodsParams',
  data() {
    return {
      categories: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        expandTrigger: 'hover'
      },
      cascader_value: [],
      // 获取属性的参数
      cateId: 0,
      sel: 'many', // 当前激活的选项卡
      attributes: [],
      // 新增标签属性
      inputVisible: false,
      inputValue: '',
      // 添加新参数
      addDialogVisible: false,
      addAttrForm: {
        attr_name: ''
      },
      addRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 8, message: '长度在 1 到 8 个字符', trigger: 'blur' }
        ]
      },
      // 编辑参数名称
      editDialogVisible: false,
      editAttrForm: {
        attr_name: ''
      }
    }
  },
  created() {
    this.getAllCategories()
    this.getAttributes()
  },
  methods: {
    async getAllCategories() {
      const { data: res } = await this.$http.get('categories')

      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      // this.$message.success(res.meta.msg)
      this.categories = res.data
    },
    // 商品分类切换
    handelChange() {
      // ? 在选中3级分类时，根据id请求参数列变进行渲染
      const len = this.cascader_value.length
      if (len === 0) {
        return false
      }
      if (len !== 3) {
        return this.$message({
          message: '只有三级类别拥有属性！',
          type: 'warning'
        })
      }
      this.cateId = this.cascader_value[len - 1]
      this.sel = 'many'
      this.getAttributes()
      // console.log(this.cascader_value)
    },
    // 获取参数列表
    async getAttributes() {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.sel
        }
      })

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      // 把字符串型的属性值转换成数组
      res.data.forEach(item => {
        if (item.attr_vals === '') {
          item.attr_vals = []
        } else {
          item.attr_vals = item.attr_vals.split(',')
        }
      })
      this.attributes = res.data
      // this.$message.success(res.meta.msg)
      console.log(this.attributes)
    },
    // 添加新的标签属性
    async submitVals(name, attrId, vals) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${attrId}`, {
        attr_name: name,
        attr_sel: this.sel,
        attr_vals: vals
      })

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 删除标签属性
    handleClose(row, tag) {
      row.attr_vals.splice(row.attr_vals.indexOf(tag), 1)
      this.submitVals(row.attr_name, row.attr_id, row.attr_vals.join(','))
    },
    // 新增标签属性提交
    async handleInputConfirm(row) {
      const inputValue = this.inputValue
      if (inputValue) {
        row.attr_vals.push(inputValue)
        // // 把新的标签提交
        this.submitVals(row.attr_name, row.attr_id, row.attr_vals.join(','))
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 显示输入tag
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 参数类别切换
    handleClick(tap) {
      this.sel = tap.name
      this.getAttributes()
      // console.log(tap)
    },
    // 添加参数
    addAttributes() {
      const len = this.cascader_value.length
      if ((len === 0) | (len !== 3)) {
        return this.$message({
          message: '请先选择合适的商品分类！',
          type: 'warning'
        })
      }

      this.addDialogVisible = true
    },
    // 关闭添加参数对话框
    closeAddAttrDialog() {
      this.$refs.addAttrForm.resetFields()

      this.addDialogVisible = false
    },
    // 打开编辑
    openEditDialog(name) {
      this.editAttrForm.attr_name = name
      this.editDialogVisible = true
    },
    // 关闭编辑对话框
    closeEditAttrDialog() {
      this.$refs.editAttrForm.resetFields()

      this.editDialogVisible = false
    },
    // 提交编辑后的属性
    submitEditedAttr() {
      this.$refs.addAttrForm.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addAttrForm.attr_name,
            attr_sel: this.sel
          })

          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }

          this.getAttributes()
          this.$message.success(res.meta.msg)
          this.addDialogVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 提交新的参数
    submitNewAttr() {
      this.$refs.addAttrForm.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addAttrForm.attr_name,
            attr_sel: this.sel,
            attr_vals: ''
          })

          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }

          this.getAttributes()
          this.$message.success(res.meta.msg)
          this.addDialogVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除参数
    async removeAttr(attrid) {
      const confirm = await this.$confirm('确认永久删除该参数？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '放弃'
      }).catch(action => {
        this.$message({
          type: 'info',
          message: action === 'cancel' ? '删除已取消' : '停留在当前页面'
        })
      })

      if (confirm !== 'confirm') {
        return false
      }

      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrid}`)

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.getAttributes()
      this.$message.success(res.meta.msg)
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 8px;
}
.select_cate {
  margin-bottom: 10px;
}
.el-table {
  margin-top: 10px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
